package com.cloudshadow.platform.server.common.base.aspect;

import com.cloudshadow.platform.infrastructure.exception.ErrInfoException;
import com.cloudshadow.platform.infrastructure.exception.ErrorInfos;
import com.cloudshadow.platform.server.common.base.utils.VoUtil;
import com.cloudshadow.platform.server.common.base.vo.BasicVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;


@Aspect
@Configuration
@Order(AspectOrders.EXCEPTION_HANDLE_ORDER)
public class ExceptionHandleAspect extends ControllerAspect {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandleAspect.class);

	@Around(value = "pointCut()")
	protected Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
		Object result = null;
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		try {
			result = pjp.proceed();
		} catch (ErrInfoException e) {
			LOGGER.error("execute failed", e);
			result = VoUtil.genErrorResult(e.getErrorNo(), e.getErrorInfo(), methodSignature.getReturnType());
		} catch (Exception e) {
			LOGGER.error("execute failed", e);
			result = VoUtil.genErrorResult(ErrorInfos.CommonErr.ERROR, methodSignature.getReturnType());
		}
		if (result instanceof BasicVo) {
			BasicVo res = (BasicVo) result;
			if (res.isSuccess()) {
				res = VoUtil.setSuccessResult(res);
			}
		}
		return result;
	}

}
